<?php

require_once("lib/customtag.php");

class View
{
    var $_vars = array();
    var $_tpl = '';
    var $_area = 'visitor';


    /**
     * Constructor
     *
     * @param string $tpl template path starting from _inc/
     * @return View
     */
    function View($tpl)
    {
        $this->setTpl($tpl);
    }


    function setArea($area)
    {
        $this->_area = $area;
    }


    /**
     * Sets template for the view 
     *
     * @param string $tpl template path starting from _inc/
     */    
    function setTpl($tpl)
    {
        $this->_tpl = _cfg('path') .'_inc/'. $tpl . '.php';
    }


    /** 
     * Gets var value
     * @param $k var name
     * @return mixed var value
     */
    function getVar($name)
    {
        return (isset($this->_vars[$name]) ? $this->_vars[$name] : '');
    }


    /** 
     * Sets var
     * @param $k var name
     * @param $v var value
     * @param $escape escape mode
     */
    function setVar($k, $v, $escape=true)
    {
        $this->_vars[$k] = ($escape ? $this->_escape($v) : $v);
    }


    /** 
     * Fetchs result into string
     * @return string
     */
    function fetch()
    {
        extract($this->_vars);
        ob_start();
        require $this->_tpl;
        $str = ob_get_clean();
        $filter = new PostFilterCTags($this->_area, $this->_vars);
        return $filter->parse($str);
    }


    /** performs html escaping
    */
    function _escape($v)
    {
        if (is_array($v))
            return array_map(array($this, '_escape'), $v);
        if (is_object($v))
            return $v;
        return htmlspecialchars($v);
    }
}
